#! /usr/bin/python

import os
import sys
import csv
import Image
import ImageStat

def conv_color(color):
    return ( int(round(color[0])), int(round(color[1])), int(round(color[2])) )

def make_index(path, out_file):
    ofile = open(out_file, "w")
    index = csv.writer(ofile)

    for root, dirs, files in os.walk(path):
        for file_name in files:
            complete_file_name = os.path.join(root, file_name)
            try:
                image = Image.open(complete_file_name).convert("RGB") # we need rgb images
            except Exception:
                print "unable to add %s to index. ignoring." % (complete_file_name)
            else:
                print "adding %s to index ..." % (complete_file_name)
                stat = ImageStat.Stat(image)
                index.writerow((complete_file_name, int(round(stat.mean[0])), int(round(stat.mean[1])), int(round(stat.mean[2]))))

    ofile.close()

def load_index(index_file):
    ifile = open(index_file)
    index = csv.reader(ifile)
    rdir = []

    for row in index:
        file_name = row[0]
        red = int(row[1])
        green = int(row[2])
        blue = int(row[3])

        rdir.append((file_name, (red, green, blue))) 

    ifile.close()
    return rdir

def color_diff(c1, c2):
    cr = c1[0] - c2[0]
    cg = c1[1] - c2[1]
    cb = c1[2] - c2[2]
    return cr * cr + cg * cg + cb * cb

def find_image(color, rdir):
    best_file = None
    best_diff = 999999999
    for h in rdir:
        diff = color_diff(h[1], color)
        if(diff < best_diff):
            best_diff = diff
            best_file = h[0]
    return best_file

def create_mosaic(idx, in_file, out_file):
    inf = Image.open(in_file)
    of = Image.new("RGB", inf.size)
    print inf.size
    w = 10
    h = 10

    x = 0
    #inf.save("t.jpg")
    while x < inf.size[0]:
        y = 0
        while y < inf.size[1]:
            
            tile = inf.crop((x, y, x + w, y + h))
            stat = ImageStat.Stat(tile)
            mean = conv_color(stat.mean)
            print mean
            #nt = Image.new("RGB", (w, h), mean)
            nt = Image.open(find_image(mean, idx)).resize((w, h))

            of.paste(nt, (x, y, x + w, y + h))

            y = y + w
        x = x + h
        print "."

    of.save("of.jpg")



# make_index("/media/sda2/Files/christoph/images", "pictures.mindex")

idx = load_index("pictures.mindex")
print find_image( (12,12,12), idx)

create_mosaic(idx, "/media/sda2/Files/christoph/images/Dsc00433.jpg", "tst")







